package com.tencent.cloud.iov.kernel.service.interceptor;

import com.tencent.cloud.iov.kernel.IovKernel;
import com.tencent.cloud.iov.kernel.constant.CommonConst;
import com.tencent.cloud.iov.kernel.constant.StatusCode;
import com.tencent.cloud.iov.kernel.service.exception.ServerException;
import com.tencent.mars.xlog.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * 状态拦截器：处理网络异常、通用响应状态码
 *
 * @author vinsonhuang
 * @date 2018/5/30
 */
public class StatusInterceptor implements Interceptor {

    private static final String TAG = StatusInterceptor.class.getSimpleName();

    private static final String CODE = "code";

    private static final String STATUS = "status";

    private static final String CONTENT_ENCODING = "Content-Encoding";

    private static final String IDENTITY = "identity";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        Response response = chain.proceed(builder.build());
        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();

        if (!bodyEncoded(response.headers())) {
            BufferedSource source = responseBody.source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();

            Charset charset = null;
            MediaType contentType = responseBody.contentType();
            if (null != contentType) {
                try {
                    charset = contentType.charset(Charset.forName(CommonConst.CHARSET));
                } catch (UnsupportedCharsetException e) {
                    return response;
                }
            }

            if (!isPlaintext(buffer)) {
                return response;
            }

            if (contentLength != 0) {
                String result = buffer.clone().readString(charset);
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(result);
                } catch (JSONException e) {
                    Log.d(TAG, "parse response body failed");
                    return response;
                }

                if (jsonObject.has(STATUS)) {
                    int status = jsonObject.optInt(STATUS);
                    if (StatusCode.SERVER_INTERNAL_ERROR == status) {
                        throw new ServerException(StatusCode.MSG_SERVER_INTERNAL_ERROR);
                    }
                } else {
                    IovKernel.handleHttpStatusCode(jsonObject.optInt(CODE));
                }
            }
        }

        return response;
    }

    private boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get(CONTENT_ENCODING);
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase(IDENTITY);
    }

    private boolean isPlaintext(Buffer buffer) {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (EOFException e) {
            // Truncated UTF-8 sequence.
            return false;
        }
    }
}
